package array;

import java.util.ArrayList;
import java.util.List;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class spiralOrder {
    public static List<Integer> spiralOrder(int[][] matrix) {
        int lenx = matrix.length;
        int leny = matrix[0].length;
        Boolean[][] help = new Boolean[lenx][leny];
        for (int i = 0; i < lenx; i++) {
            for (int j = 0; j < leny; j++) {
                help[i][j] = false;
            }
        }
        int round = Math.min(lenx, leny)/2;
        int i,j;
        int startx=0, starty=0;
        int count = 1;
        List<Integer> result = new ArrayList<>();
        while (round >= 0){
            i = startx;
            j = starty;
            for (; j < leny-count; j++) {
                if (!help[i][j]){
                    result.add(matrix[i][j]);
                    help[i][j] = true;
                }else {
                    break;
                }
            }
            for (; i < lenx-count; i++) {
                if (!help[i][j]){
                    result.add(matrix[i][j]);
                    help[i][j] = true;
                }else {
                    break;
                }

            }
            for (;j > starty; j--){
                if (!help[i][j]){
                    result.add(matrix[i][j]);
                    help[i][j] = true;
                }else {
                    break;
                }
            }
            for (; i > startx; i--){
                if (!help[i][j]){
                    result.add(matrix[i][j]);
                    help[i][j] = true;
                }else {
                    break;
                }
            }
            startx++;
            starty++;
            count++;
            round--;
        }
        if (lenx == leny && lenx%2 != 0){
            result.add(matrix[lenx/2][leny/2]);
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] a = {{2, 3, 4},
                {5, 6, 7},
                {8, 9, 10},
                {11, 12, 13},
                {14, 15, 16}};
        System.out.println(spiralOrder(a));
    }
}
